import * as echarts from 'echarts'
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react'
import CountUp from 'react-countup'
import Slider from 'react-slick'

import { ViolationCategoryData } from '../../data'
import CarouselBox from './CarouselBox'
import LengedDataBox from './LengedDataBox'

import 'animate.css'
import 'slick-carousel/slick/slick-theme.css'
import 'slick-carousel/slick/slick.css'

export type SecurityGovernancePieProps = {
  chartData: ViolationCategoryData[]
  colors: string[][]
}

export type SecurityGovernancePieRef = {
  resize: () => void
}

const SecurityGovernancePie = forwardRef<
  SecurityGovernancePieRef,
  SecurityGovernancePieProps
>(({ chartData = [], colors }, ref) => {
  const chartDom = useRef<HTMLDivElement>(null)
  const myChart = useRef<echarts.EChartsType>()
  const [activeIndex, setIndex] = useState<number>(-1)
  const timerPieRef = useRef<any>(null)
  const [settings, setSetings] = useState<any>({
    dots: false, // 隐藏轮播小圆点
    infinite: true,
    slidesToShow: 6, // 展示6条内容
    speed: 500,
    autoplay: true,
    vertical: true, // 垂直
    autoplaySpeed: 2000,
    pauseOnHover: true, // 鼠标悬浮不暂停
    arrows: false // 隐藏翻页箭头
  })

  const sliderRef = useRef<any>(null) // 图例轮播的配置
  const [playAnimation, setPlayAnimation] = useState(false) // 体积占比的动画

  const clickFun = (index: number) => {
    if (timerPieRef.current) clearInterval(timerPieRef.current)

    setIndex(index)

    chartData?.map((v, i) => {
      // 取消之前高亮的图形
      myChart.current?.dispatchAction({
        type: 'downplay',
        seriesIndex: 0,
        dataIndex: i
      })
    })

    myChart.current?.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: index
    })
  }

  useEffect(() => {
    if (!chartDom.current) return

    const optData = chartData?.filter((v) => v.value)

    let fData: any[] = []

    if (optData.length) {
      fData = chartData
    }

    const updatedChartData = fData?.map((v, i) => {
      return {
        name: v.name,
        value: v.value,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: colors[i][0] },
              { offset: 1, color: colors[i][1] }
            ],
            global: false
          }
        }
      }
    })

    if (!myChart.current) {
      initOption()
    }

    if (myChart.current) {
      myChart?.current?.setOption({
        series: [
          {
            data: updatedChartData
          }
        ]
      })

      setIndex(0)
      myChart.current.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: 0
      })

      myChart.current.on('mouseout', function (params) {
        clearInterval(timerPieRef.current)
        startPieTime()
      })

      myChart.current.on('click', function (params) {
        clickFun(params.dataIndex)
      })
    }
  }, [chartData])

  useEffect(() => {
    return () => {
      if (myChart.current && !myChart.current.isDisposed()) {
        echarts.dispose(myChart.current)
      }
    }
  }, [])

  useEffect(() => {
    setSetings({
      ...settings,
      slidesToShow: chartData && chartData.length > 5 ? 6 : chartData.length
    })

    if (timerPieRef.current) clearInterval(timerPieRef.current)

    startPieTime()
  }, [chartData])

  const initOption = () => {
    myChart.current = echarts.init(chartDom.current, null, {
      renderer: 'canvas'
    })

    myChart.current.setOption({
      showEmptyCircle: true,
      series: [
        {
          type: 'pie',
          radius: ['68%', '90%'],
          center: ['center', 'center'],
          label: {
            show: false
          },
          labelLine: {
            show: false
          },
          itemStyle: {
            borderColor: '#181818',
            borderWidth: 2
          },
          avoidLabelOverlap: true,
          animation: true,
          hoverAnimation: true,
          emphasis: {
            scale: true,
            scaleSize: 8,
            label: {
              show: false
            }
          },
          emptyCircleStyle: {
            color: 'rgba(0, 0, 0, 0.60)'
          }
        }
      ]
    })
  }

  const startPieTime = () => {
    let currentIndex = activeIndex

    if (chartData && myChart.current) {
      timerPieRef.current = setInterval(function () {
        if (myChart.current) {
          const dataLen = chartData.length
          currentIndex = currentIndex < dataLen - 1 ? currentIndex + 1 : 0

          setIndex(currentIndex)
          // 取消之前高亮的图形
          chartData.map((v: any, i: number) => {
            // 取消之前高亮的图形
            myChart.current?.dispatchAction({
              type: 'downplay',
              seriesIndex: 0,
              dataIndex: i
            })
          })

          // 高亮当前图形
          myChart.current.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: currentIndex
          })
        }
      }, 2411)
    }
  }

  useEffect(() => {
    return () => {
      if (timerPieRef.current) {
        clearInterval(timerPieRef.current)
      }
    }
  }, [])

  useEffect(() => {
    startAnimation()
  }, [activeIndex])

  const startAnimation = () => {
    setPlayAnimation(true)
    setTimeout(() => {
      setPlayAnimation(false)
    }, 3000) // 5秒后停止动画
  }

  /*视口改变 echarts  -resize*/
  useImperativeHandle(ref, () => ({
    resize: () => {
      if (myChart.current) {
        myChart.current.resize()
      }
    }
  }))

  return (
    <div
      className="pie-box flexr alc juc"
      style={{ position: 'relative', height: '100%' }}
    >
      <div
        className="flexr alc juc"
        style={{ position: 'relative', width: 358, height: '100%' }}
      >
        {/* 环形图 */}
        <div className="flexr alc juc" style={{ position: 'relative' }}>
          {/* 环形图 -中间的数据*/}
          <div className="card-abs">
            <div className="item-p" style={{ color: colors[activeIndex]?.[2] }}>
              <CountUp
                start={0}
                end={
                  chartData && activeIndex > -1
                    ? chartData[activeIndex]?.piont
                    : (chartData && chartData[0]?.piont) || 0
                }
                duration={1}
                decimals={2}
              />
              <span className="p-t">%</span>
            </div>
            <CarouselBox
              data={chartData}
              dataIndex={activeIndex || 0}
              color={colors}
            />
          </div>
          {/* 环形图 -本身*/}
          <div
            ref={chartDom}
            style={{ width: '152px', minHeight: '152px' }}
            className="echarts-pie"
          ></div>
        </div>

        {/* 环形图 - 右侧图例*/}
        <div className="SliderContent2" style={{ marginLeft: 20 }}>
          {chartData.length > 6 ? (
            <>
              <Slider ref={sliderRef} {...settings}>
                {chartData.map((item: any, i: number) => {
                  return (
                    <LengedDataBox
                      label={item.name}
                      value={item.piont}
                      key={i}
                      color={colors[i]?.[2]}
                    />
                  )
                })}
              </Slider>
            </>
          ) : (
            <>
              {chartData.map((item: any, i: number) => {
                return (
                  <LengedDataBox
                    label={item.name}
                    value={item.piont}
                    key={i}
                    color={colors[i]?.[2]}
                  />
                )
              })}
            </>
          )}
        </div>
      </div>
    </div>
  )
})

export default SecurityGovernancePie
